/*
 * @lc app=leetcode.cn id=5 lang=javascript
 *
 * [5] 最长回文子串
 */

// @lc code=start
/**
 * @param {string} s
 * @return {string}
 */
var longestPalindrome = function (s) {
    return doublePoint(s)
};

// 双指针法
function doublePoint(s) {
    let maxlen = 0
    let ans = ''
    for (let i = 0; i < s.length; i++) {
        let ans1 = getAns(i, i, s, maxlen)
        if (ans1) {
            ans = ans1
            maxlen = ans1.length
        }
        let ans2 = getAns(i, i + 1, s, maxlen)
        if (ans2) {
            ans = ans2
            maxlen = ans2.length
        }
    }
    return ans
}

function getAns(left, right, s, maxlen) {
    let done = false
    let begin = 0
    while (left >= 0 && right < s.length && s[left] == s[right]) {
        if (right - left + 1 > maxlen) {
            done = true
            maxlen = right - left + 1
            begin = left
        }
        left--
        right++
    }
    if (done) return s.substr(begin, maxlen)
    else return ''
}
// @lc code=end
// @after-stub-for-debug-begin
module.exports = longestPalindrome;
// @after-stub-for-debug-end